package com.superm.controller;

import com.superm.entity.Department;
import com.superm.mappers.EmpMapper;
import com.superm.service.DepartmentService;
import com.superm.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(path="/department")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private EmpService empService;
    @RequestMapping("/index")
    public String index(){
        return "department/allDep";
    }

    @RequestMapping(path = "/allDep")
    @ResponseBody//展示所有部门信息
    public Map<String,Object> allDep(){
        Map<String,Object> map = new HashMap<>();
        List<Department> deps = departmentService.allDepartment();
        map.put("code",0);
        map.put("data",deps);
        return map;
    }
    @RequestMapping("/allup")//跳转到添加修改页面
    public ModelAndView allup(String sign,Integer did){
        ModelAndView ma = new ModelAndView();
        Department dep = departmentService.depId(did);
        ma.addObject("dep",dep);
        ma.addObject("sign",sign);
        ma.setViewName("department/addupDep");
        return ma;
    }
    @RequestMapping(path = "/allupDep")
    @ResponseBody//确认添加修改
    public Map<String,Object> allupDep(Department dep,String sign) {
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        if(sign.equals("add")){
            if(departmentService.addDepartment(dep)>0){
                map.put("success",true);
                map.put("msg","添加成功!");
                return map;
            }
            map.put("success",false);
            map.put("msg","添加失败!");
        }else{
            if(departmentService.upDepartment(dep)>0){
                map.put("success",true);
                map.put("msg","修改成功!");
                return map;
            }
            map.put("success",false);
            map.put("msg","修改失败!");
        }
        return map;
    }
    @RequestMapping(path = "/delDep")
    @ResponseBody//确认删除部门
    public Map<String,Object> delDep(Integer did){
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        if(empService.EmpCount(did)>0){
            map.put("success", false);
            map.put("msg", "该部门有员工引用!");
            return map;
        }else{
            if(departmentService.delDepartment(did)>0) {
                map.put("success", true);
                map.put("msg", "删除成功!");
                return map;
            }else{
                map.put("success",false);
                map.put("msg","删除失败!");
            }
        }
        return map;
    }
}
